﻿using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace Rio.Framework.Pages.AppCode.Helpers
{
    public class LoadingIndicatorManager : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private Stack<Guid> _stackTasks;

        /// <summary>
        /// Gets or sets a value indicating whether this instance is busy.
        /// </summary>
        /// <value>
        ///   <c>true</c> if this instance is busy; otherwise, <c>false</c>.
        /// </value>
        public bool IsBusy
        {
            get
            {
                return _stackTasks.Count == 0 ? false : true;
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="LoadingIndicatorManager"/> class.
        /// </summary>
        public LoadingIndicatorManager()
        {
            _stackTasks = new Stack<Guid>();
        }

        /// <summary>
        /// Adds the busy task.
        /// </summary>
        public void AddBusyTask()
        {
            _stackTasks.Push(Guid.NewGuid());

            OnPropertyChanged("IsBusy");
        }

        /// <summary>
        /// Removes the busy task.
        /// </summary>
        public void RemoveBusyTask()
        {
            if (_stackTasks.Count > 0)
                _stackTasks.Pop();

            OnPropertyChanged("IsBusy");
        }

        /// <summary>
        /// Clear
        /// </summary>
        public void Clear()
        {
            _stackTasks.Clear();

            OnPropertyChanged("IsBusy");
        }

        /// <summary>
        /// Called when [property changed].
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(null, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
